<template>
  <BasicDrawer
    v-bind="$attrs"
    showFooter
    @register="channelRegister"
    width="1000"
    :extraScrollHeight="57"
    isAbsolute
    @ok="confirmSubmit"
    @close="drawerReset"
    getContainer=".page-wrapper"
  >
    <template #contentExtra>
      <div class="drawer-tab">
        <template v-for="item in tabObj.tabList" :key="item.key">
          <div
            v-if="item.isShow"
            :class="['tab-item', item.key === tabObj.activeKey ? 'tab-active' : '']"
            @click="tabHandle(item.key)"
          >
            {{ item.tab }}
          </div>
        </template>
      </div>
    </template>
    <div class="box-drawer" v-loading="infoLoading">
      <div v-show="tabObj.activeKey === '1'" class="box-product">
        <div class="product-nav">
          <div
            :class="['nav-item', navActive === index ? 'nav-active' : '']"
            @click="navScroll(index)"
            v-for="(item, index) in tabJump"
            :key="item"
          >
            {{ item }}
          </div>
        </div>
        <div class="channel-form" v-if="drawerInfo.type !== operateActionType.VIEW" @scroll="scrollHandle">
          <div class="channel-tip">
            <info-circle-outlined :style="{ fontSize: '24px', marginRight: '14px', color: '#2a64f6' }" />
            <div class="tip-txt">注意：品牌配置请谨慎修改，配置一旦保存将影响该渠道伙伴下的所有企业界面的展示。</div>
          </div>
          <a-form
            ref="formRef"
            :colon="false"
            autocomplete="off"
            :label-col="{ style: { width: '120px' } }"
            :model="drawerInfo"
            :rules="getFormRules"
            lableWidth
          >
            <div class="channel-box">
              <div class="channel-custom">
                <a-form-item label="自定义开关" name="switchFlag">
                  <a-switch
                    v-model:checked="drawerInfo.switchFlag"
                    :checkedValue="1"
                    :unCheckedValue="2"
                    checked-children="启用"
                    un-checked-children="关闭"
                  />
                </a-form-item>
                <info-circle-outlined class="icon" />
                <span class="describe">说明：开启后，即可自定义渠道自定义信息</span>
              </div>
              <div class="channel-custom">
                <a-form-item label="注册短信开关" name="sendMsgFlag">
                  <a-switch
                    v-model:checked="drawerInfo.sendMsgFlag"
                    :checkedValue="1"
                    :unCheckedValue="2"
                    checked-children="启用"
                    un-checked-children="关闭"
                  />
                </a-form-item>
                <info-circle-outlined class="icon" />
                <span class="describe">说明：关闭后，在运营后台新增企业则不发送通知短信</span>
              </div>
              <div class="title scroll-item">链接自定义</div>
              <div class="service" style="margin-bottom: 0">
                <div class="service-btn">
                  <a-form-item label="专属登录链接">
                    <a-input
                      disabled
                      placeholder="点击生成按钮生成链接"
                      v-model:value.trim="drawerInfo.channelLoginUrl"
                    >
                    </a-input>
                  </a-form-item>
                  <a-button
                    type="primary"
                    class="btn-link"
                    @click="linkHandle('loginUrl')"
                    :loading="loadingObj.logoLoading"
                  >
                    {{ drawerInfo.channelLoginUrl ? '复制链接' : '生成链接' }}
                  </a-button>
                </div>
                <div class="service-btn">
                  <a-form-item label="客户端专属下载链接">
                    <a-input
                      disabled
                      placeholder="点击生成按钮生成链接"
                      v-model:value.trim="drawerInfo.channelDownloadUrl"
                    >
                    </a-input>
                  </a-form-item>
                  <a-button
                    type="primary"
                    class="btn-link"
                    @click="linkHandle('downloadUrl')"
                    :loading="loadingObj.downLoading"
                  >
                    {{ drawerInfo.channelDownloadUrl ? '复制链接' : '生成链接' }}
                  </a-button>
                </div>
                <div class="service-btn">
                  <a-form-item label="移动端专属登录链接">
                    <a-input
                      disabled
                      placeholder="点击生成按钮生成链接"
                      v-model:value.trim="drawerInfo.mobileChannelLoginUrl"
                    >
                    </a-input>
                  </a-form-item>
                  <a-button
                    type="primary"
                    class="btn-link"
                    @click="linkHandle('mobileChannelLoginUrl')"
                    :loading="loadingObj.mobileChannelLoginUrlLoading"
                  >
                    {{ drawerInfo.mobileChannelLoginUrl ? '复制链接' : '生成链接' }}
                  </a-button>
                </div>
                <div class="channel-custom channel-custom-invoice">
                  <a-form-item label="一键唤起开票软件" name="oneClickInvoiceSoftwareFlag">
                    <a-switch
                      v-model:checked="drawerInfo.oneClickInvoiceSoftwareFlag"
                      :checkedValue="1"
                      :unCheckedValue="2"
                      checked-children="启用"
                      un-checked-children="关闭"
                    />
                  </a-form-item>
                </div>
              </div>
              <div class="title scroll-item">logo自定义</div>
              <div class="uploadLogo">
                <a-form-item name="uploadspt" label="登录/注册页logo">
                  <a-upload
                    v-model:dllogoList="dllogoList"
                    name="loginRegisterLogo"
                    accept="image/png"
                    list-type="picture-card"
                    :disabled="dlloading"
                    class="avatar-uploader"
                    :show-upload-list="false"
                    :before-upload="beforeUpload"
                    :customRequest="handleDlRequest"
                  >
                    <template v-if="drawerInfo?.loginRegisterLogo">
                      <img :src="drawerInfo?.loginRegisterLogo" alt="登录/注册页logo" :width="314" :height="40" />
                      <close-circle-filled class="file-close" @click.stop="drawerInfo.loginRegisterLogo = ''" />
                    </template>
                    <div class="inner-info" v-else style="width: 314px; height: 40px">
                      <loading-outlined v-if="dlloading"></loading-outlined>
                      <upload-outlined v-else></upload-outlined>
                      <div class="ant-upload-text">上传图片</div>
                    </div>
                  </a-upload>
                  <div class="upload-info">
                    <info-circle-outlined class="info-icon" />
                    只支持png格式，942px*120px
                  </div>
                </a-form-item>
                <a-form-item name="uploadspt" label="数票通logo">
                  <a-upload
                    v-model:sptlogoList="sptlogoList"
                    name="sptlogo"
                    accept="image/png"
                    list-type="picture-card"
                    :disabled="sptloading"
                    class="avatar-uploader"
                    :show-upload-list="false"
                    :before-upload="beforeUpload"
                    :customRequest="handleSptRequest"
                  >
                    <template v-if="drawerInfo?.sptlogo">
                      <img :src="drawerInfo?.sptlogo" alt="数票通图片" :width="242" :height="40" />
                      <close-circle-filled class="file-close" @click.stop="drawerInfo.sptlogo = ''" />
                    </template>
                    <div class="inner-info" v-else style="width: 242px; height: 40px">
                      <loading-outlined v-if="sptloading"></loading-outlined>
                      <upload-outlined v-else></upload-outlined>
                      <div class="ant-upload-text">上传图片</div>
                    </div>
                  </a-upload>
                  <div class="upload-info">
                    <info-circle-outlined class="info-icon" />
                    只支持png格式，720px*114px
                  </div>
                </a-form-item>
                <a-form-item name="uploadyc" label="财税BPailogo">
                  <a-upload
                    v-model:yclogoList="yclogoList"
                    name="yclogo"
                    list-type="picture-card"
                    accept="image/png"
                    class="avatar-uploader"
                    :show-upload-list="false"
                    :disabled="ycloading"
                    :before-upload="beforeUpload"
                    :customRequest="handleYcRequest"
                  >
                    <template v-if="drawerInfo?.yclogo">
                      <img :src="drawerInfo?.yclogo" alt="数票通图片" :width="202" :height="57" />
                      <close-circle-filled class="file-close" @click.stop="drawerInfo.yclogo = ''" />
                    </template>
                    <div class="inner-info" v-else style="width: 202px; height: 57px">
                      <loading-outlined v-if="ycloading"></loading-outlined>
                      <upload-outlined v-else></upload-outlined>
                      <div class="ant-upload-text">上传图片</div>
                    </div>
                  </a-upload>
                  <div class="upload-info">
                    <info-circle-outlined class="info-icon" />
                    只支持png格式，600px*165px
                  </div>
                </a-form-item>
                <a-form-item name="mobileLoginRegisterLogo" label="移动端登录页logo">
                  <a-upload
                    v-model:mobilelogoList="mobilelogoList"
                    name="mobileLoginRegisterLogo"
                    list-type="picture-card"
                    accept="image/png"
                    class="avatar-uploader"
                    :show-upload-list="false"
                    :disabled="mobileloading"
                    :before-upload="beforeUpload"
                    :customRequest="handleMobileRequest"
                  >
                    <template v-if="drawerInfo?.mobileLoginRegisterLogo">
                      <img
                        :src="drawerInfo?.mobileLoginRegisterLogo"
                        alt="移动端登录页logo"
                        :width="335"
                        :height="70"
                      />
                      <close-circle-filled class="file-close" @click.stop="drawerInfo.mobileLoginRegisterLogo = ''" />
                    </template>
                    <div class="inner-info" v-else style="width: 335px; height: 70px">
                      <loading-outlined v-if="mobileloading"></loading-outlined>
                      <upload-outlined v-else></upload-outlined>
                      <div class="ant-upload-text">上传图片</div>
                    </div>
                  </a-upload>
                  <div class="upload-info">
                    <info-circle-outlined class="info-icon" />
                    只支持png格式，1005px*210px
                  </div>
                </a-form-item>
              </div>
              <div class="title scroll-item">网页端客服信息</div>
              <div class="service">
                <a-form-item label="联系客服链接" name="serviceLink">
                  <a-input
                    allowClear
                    placeholder="请输入联系客服链接"
                    v-model:value.trim="drawerInfo.serviceLink"
                    @input="drawerInfo.servicePhone = ''"
                    :maxlength="500"
                  >
                  </a-input>
                </a-form-item>
                <a-form-item label="联系客服电话" name="servicePhone">
                  <a-input
                    allowClear
                    placeholder="请输入联系客服电话"
                    v-model:value.trim="drawerInfo.servicePhone"
                    @input="drawerInfo.serviceLink = ''"
                    :maxlength="50"
                  >
                  </a-input>
                </a-form-item>
                <div class="uploadLogo uploadCustomer">
                  <a-form-item name="customerServiceQrCode" label="客服二维码">
                    <a-upload
                      name="customerServiceQrCode"
                      list-type="picture-card"
                      accept="image/png"
                      class="avatar-uploader"
                      :show-upload-list="false"
                      :disabled="customerQrloading"
                      :before-upload="beforeUpload"
                      :customRequest="handleCustomerQrRequest"
                    >
                      <template v-if="drawerInfo?.customerServiceQrCode">
                        <img :src="drawerInfo?.customerServiceQrCode" alt="客服二维码" :width="126" :height="126" />
                        <close-circle-filled class="file-close" @click.stop="drawerInfo.customerServiceQrCode = ''" />
                      </template>
                      <div class="inner-info" v-else style="width: 126px; height: 126px">
                        <loading-outlined v-if="customerQrloading"></loading-outlined>
                        <upload-outlined v-else></upload-outlined>
                        <div class="ant-upload-text">上传图片</div>
                      </div>
                    </a-upload>
                    <div class="upload-info">
                      <info-circle-outlined class="info-icon" />
                      只支持png格式，384*384px
                    </div>
                  </a-form-item>
                </div>
              </div>
              <div class="title scroll-item">H5客服信息</div>
              <div class="service box-desc">
                <div class="uploadLogo uploadCustomer">
                  <a-form-item name="h5CustomerServiceUrl" label="联系客服二维码">
                    <a-upload
                      v-model:customerlogoList="customerlogoList"
                      name="customerlogo"
                      list-type="picture-card"
                      accept="image/png"
                      class="avatar-uploader"
                      :show-upload-list="false"
                      :disabled="customerloading"
                      :before-upload="beforeUpload"
                      :customRequest="handleCustomerRequest"
                    >
                      <template v-if="drawerInfo?.h5CustomerServiceUrl">
                        <img :src="drawerInfo?.h5CustomerServiceUrl" alt="联系客服二维码" :width="126" :height="126" />
                        <close-circle-filled class="file-close" @click.stop="drawerInfo.h5CustomerServiceUrl = ''" />
                      </template>
                      <div class="inner-info" v-else style="width: 126px; height: 126px">
                        <loading-outlined v-if="customerloading"></loading-outlined>
                        <upload-outlined v-else></upload-outlined>
                        <div class="ant-upload-text">上传图片</div>
                      </div>
                    </a-upload>
                    <div class="upload-info">
                      <info-circle-outlined class="info-icon" />
                      只支持png格式，384*384px
                    </div>
                  </a-form-item>
                </div>

                <a-form-item label="合作伙伴宣传语" name="h5Slogans">
                  <a-input
                    allowClear
                    placeholder="请输入合作伙伴宣传语"
                    v-model:value.trim="drawerInfo.h5Slogans"
                    :maxlength="50"
                  >
                  </a-input>
                </a-form-item>
                <a-form-item label="合作伙伴联系信息" name="h5ContactInfo">
                  <a-input
                    allowClear
                    placeholder="请输入合作伙伴联系信息"
                    v-model:value="drawerInfo.h5ContactInfo"
                    :maxlength="50"
                  >
                  </a-input>
                </a-form-item>
              </div>
              <div class="title scroll-item">桌牌开票自定义</div>
              <div class="service box-desc">
                <a-form-item label="商家宣传语" name="sellerSlogan">
                  <a-input
                    allowClear
                    placeholder="请输入商家宣传语"
                    v-model:value.trim="drawerInfo.sellerSlogan"
                    :maxlength="20"
                  >
                  </a-input>
                </a-form-item>
                <a-form-item label="商家联系信息" name="sellerInfo">
                  <a-input
                    allowClear
                    placeholder="请输入商家联系信息"
                    v-model:value="drawerInfo.sellerInfo"
                    :maxlength="20"
                  >
                  </a-input>
                </a-form-item>
              </div>
              <div class="preview edit">
                <a-descriptions :column="1" :colon="false">
                  <a-descriptions-item label="预览信息" style="padding-bottom: 24px">
                    <div class="staticCode">
                      <div class="QRcode"></div>
                      <div class="slogan">{{ drawerInfo.sellerSlogan }}</div>
                      <div class="contactInfo">{{ drawerInfo.sellerInfo }}</div>
                    </div>
                  </a-descriptions-item>
                </a-descriptions>
              </div>
              <div class="title scroll-item">小票开票自定义</div>
              <div class="service box-desc">
                <a-form-item label="渠道宣传语" name="channelSlogans">
                  <a-input
                    allowClear
                    placeholder="请输入渠道宣传语"
                    v-model:value.trim="drawerInfo.channelSlogans"
                    :maxlength="20"
                  >
                  </a-input>
                </a-form-item>
                <a-form-item label="商务合作信息" name="channelContactInfo">
                  <a-input
                    allowClear
                    placeholder="请输入商务合作信息"
                    v-model:value="drawerInfo.channelContactInfo"
                    :maxlength="20"
                  >
                  </a-input>
                </a-form-item>
              </div>
            </div>
          </a-form>
        </div>
        <div class="channel-view" v-if="drawerInfo.type === operateActionType.VIEW" @scroll="scrollHandle">
          <div class="channel-tip">
            <info-circle-outlined :style="{ fontSize: '24px', marginRight: '14px', color: '#2a64f6' }" />
            <div class="tip-txt">注意：品牌配置请谨慎修改，配置一旦保存将影响该渠道伙伴下的所有企业界面的展示。</div>
          </div>
          <div class="channelBox">
            <div class="channel-custom" style="padding-left: 94px">
              <a-form-item label="自定义开关" name="switchFlag" required>
                <a-switch
                  v-model:checked="drawerInfo.switchFlag"
                  :checkedValue="1"
                  :unCheckedValue="2"
                  checked-children="启用"
                  un-checked-children="关闭"
                  disabled
                />
              </a-form-item>
              <info-circle-outlined class="icon" />
              <span class="describe">说明：开启后，即可自定义渠道自定义信息</span>
            </div>
            <div class="channel-custom" style="padding-left: 81px">
              <a-form-item label="注册短信开关" name="sendMsgFlag" required>
                <a-switch
                  v-model:checked="drawerInfo.sendMsgFlag"
                  :checkedValue="1"
                  :unCheckedValue="2"
                  checked-children="启用"
                  un-checked-children="关闭"
                  disabled
                />
              </a-form-item>
              <info-circle-outlined class="icon" />
              <span class="describe">说明：关闭后，在运营后台新增企业则不发送通知短信</span>
            </div>
            <div class="title scroll-item">链接自定义</div>
            <div class="service box-desc">
              <a-descriptions :column="1" :colon="false">
                <a-descriptions-item label="专属登录链接">{{ drawerInfo.record.channelLoginUrl }}</a-descriptions-item>
                <a-descriptions-item label="客户端专属下载链接">
                  {{ drawerInfo.record.channelDownloadUrl }}
                </a-descriptions-item>
                <a-descriptions-item label="移动端专属登录链接">
                  {{ drawerInfo.record.mobileChannelLoginUrl }}
                </a-descriptions-item>
                <a-descriptions-item label="一键唤起开票软件">
                  <div class="channel-custom channel-custom-invoice">
                    <a-switch
                      v-model:checked="drawerInfo.oneClickInvoiceSoftwareFlag"
                      :checkedValue="1"
                      :unCheckedValue="2"
                      checked-children="启用"
                      un-checked-children="关闭"
                      disabled
                    />
                  </div>
                </a-descriptions-item>
              </a-descriptions>
            </div>
            <div class="title scroll-item">logo自定义</div>
            <div class="uploadLogo box-desc">
              <a-descriptions :column="1" :colon="false">
                <a-descriptions-item label="登录/注册页logo" class="image"
                  ><a-image
                    :src="drawerInfo.record.loginRegisterLogo"
                    :width="314"
                    :height="40"
                    :preview="false"
                    alt="登录/注册页logo"
                    v-if="drawerInfo.record.loginRegisterLogo"
                  />
                </a-descriptions-item>
                <a-descriptions-item label="数票通logo" class="image"
                  ><a-image
                    :src="drawerInfo.sptlogo"
                    :width="242"
                    :height="40"
                    :preview="false"
                    alt="数票通logo"
                    v-if="drawerInfo.sptlogo"
                  />
                </a-descriptions-item>
                <a-descriptions-item label="财税BPailogo" class="image"
                  ><a-image
                    :width="202"
                    :height="57"
                    :src="drawerInfo.yclogo"
                    :preview="false"
                    alt="财税BPailogo"
                    v-if="drawerInfo.yclogo"
                /></a-descriptions-item>
                <a-descriptions-item label="移动端登录页logo" class="image"
                  ><a-image
                    :width="335"
                    :height="70"
                    :src="drawerInfo.mobileLoginRegisterLogo"
                    :preview="false"
                    alt="移动端登录页logo"
                    v-if="drawerInfo.mobileLoginRegisterLogo"
                /></a-descriptions-item>
              </a-descriptions>
            </div>
            <div class="title scroll-item">网页端客服信息</div>
            <div class="service box-desc">
              <a-descriptions :column="1" :colon="false">
                <a-descriptions-item label="联系客服链接">{{ drawerInfo.serviceLink }}</a-descriptions-item>
                <a-descriptions-item label="联系客服电话">{{ drawerInfo.servicePhone }}</a-descriptions-item>
                <a-descriptions-item label="客服二维码" class="image"
                  ><a-image
                    :width="126"
                    :height="126"
                    :src="drawerInfo.customerServiceQrCode"
                    :preview="false"
                    alt="联系客服二维码"
                    v-if="drawerInfo.customerServiceQrCode"
                /></a-descriptions-item>
              </a-descriptions>
            </div>
            <div class="title scroll-item">H5客服信息</div>
            <div class="service box-desc">
              <a-descriptions :column="1" :colon="false">
                <a-descriptions-item label="联系客服二维码" class="image"
                  ><a-image
                    :width="126"
                    :height="126"
                    :src="drawerInfo.h5CustomerServiceUrl"
                    :preview="false"
                    alt="联系客服二维码"
                    v-if="drawerInfo.h5CustomerServiceUrl"
                /></a-descriptions-item>
                <a-descriptions-item label="合作伙伴宣传语">{{ drawerInfo.h5Slogans }}</a-descriptions-item>
                <a-descriptions-item label="合作伙伴联系信息">{{ drawerInfo.h5ContactInfo }}</a-descriptions-item>
              </a-descriptions>
            </div>
            <div class="title scroll-item">桌牌开票自定义</div>
            <div class="service box-desc">
              <a-descriptions :column="1" :colon="false">
                <a-descriptions-item label="商家宣传语">{{ drawerInfo.sellerSlogan }}</a-descriptions-item>
                <a-descriptions-item label="商家联系信息">{{ drawerInfo.sellerInfo }}</a-descriptions-item>

                <a-descriptions-item label="预览信息" class="preview">
                  <div class="staticCode staticCodeView">
                    <div class="QRcode"></div>
                    <div class="slogan">{{ drawerInfo.sellerSlogan }}</div>
                    <div class="contactInfo">{{ drawerInfo.sellerInfo }}</div>
                  </div>
                </a-descriptions-item>
              </a-descriptions>
            </div>
            <div class="title scroll-item">小票开票自定义</div>
            <div class="service box-desc" style="margin-bottom: 24px">
              <a-descriptions :column="1" :colon="false">
                <a-descriptions-item label="渠道宣传语">{{ drawerInfo.channelSlogans }}</a-descriptions-item>
                <a-descriptions-item label="商务合作信息">{{ drawerInfo.channelContactInfo }}</a-descriptions-item>
              </a-descriptions>
            </div>
          </div>
        </div>
      </div>
      <div v-show="tabObj.activeKey === '2'">
        <PackageSet ref="packageSetRef" :operateType="drawerInfo.type" :packageSetData="drawerInfo.packageSetData" />
      </div>
    </div>
  </BasicDrawer>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, unref } from 'vue'
import { BasicDrawer, useDrawerInner } from '@/components/Drawer'
import { operateActionType } from '@/types/enum'
import { InfoCircleOutlined, UploadOutlined, LoadingOutlined, CloseCircleFilled } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import type { UploadProps } from 'ant-design-vue'
import { cloneDeep, debounce } from 'lodash-es'
import PackageSet from './PackageSet.vue'
import api from '@/api'
import ObsClient from 'esdk-obs-browserjs/src/obs'
import { obsUpAndDownload } from '@/utils/file/obs'
import useClipboard from 'vue-clipboard3'
import { userStore } from '@/store/modules/user'
import { permissionCodeMap } from '@/utils/permissionCodeMap'

const { updateChannelConfig, uploadLogo, generateChannelLoginUrlOrDownloadUrl, getPackageConfig, saveOrUpdate } = api

const userModule = userStore()

const { toClipboard } = useClipboard()

const emit = defineEmits(['operateSuccess', 'register'])

const packageSetRef = ref()
const infoLoading = ref(false)
const sptloading = ref<boolean>(false)
const dlloading = ref<boolean>(false)
const ycloading = ref<boolean>(false)
const mobileloading = ref<boolean>(false)
const customerloading = ref<boolean>(false)
const customerQrloading = ref<boolean>(false)
const formRef = ref()
const sptlogoList = ref([])
const dllogoList = ref([])
const yclogoList = ref([])
const mobilelogoList = ref([])
const customerlogoList = ref([])
let obsClient: any
let expiresTime: Date

const tabJump = ['链接自定义', 'logo自定义', '网页端客服信息', 'H5客服信息', '桌牌开票自定义', '小票开票自定义']
const navActive = ref(0)
const tabObj = reactive({
  activeKey: '1',
  tabList: [
    {
      key: '1',
      tab: '品牌配置',
      isShow: true
    },
    {
      key: '2',
      tab: '套餐配置',
      isShow: true
    }
  ]
})

const drawerInfo = reactive<any>({
  type: '',
  record: {},
  packageSetData: {}, // 套餐配置
  sptlogo: '', //数票通logo
  loginRegisterLogo: '', //登录注册logo
  yclogo: '', //业财360logo
  mobileLoginRegisterLogo: '', //移动端登录页logo
  serviceLink: '', //客服链接
  servicePhone: '', //客服联系方式
  h5ContactInfo: '', //H5-合作伙伴联系信息
  h5CustomerServiceUrl: '', //H5-联系客服二维码链接
  customerServiceQrCode: '', //pc-联系客服二维码链接
  h5Slogans: '', //H5-合作伙伴宣传语
  sellerSlogan: '', //商家宣传语
  channelSlogans: '', //渠道宣传语
  channelContactInfo: '', //商务合作信息
  channelDownloadUrl: '', //专属下载链接
  channelLoginUrl: '', //专属登录链接
  mobileChannelLoginUrl: '', //专属登录链接
  sellerInfo: '', //商家联系信息
  oneClickInvoiceSoftwareFlag: 1, //一键唤起软件
  switchFlag: 1, //自定义开关
  sendMsgFlag: 1 //注册短信开关
})

const loadingObj = reactive({
  logoLoading: false,
  downLoading: false,
  mobileChannelLoginUrlLoading: false
})
const getObsClient = async () => {
  let res = await uploadLogo({
    dir: `psy-public/${import.meta.env.VITE_OBS_DIR}/UI/channel`
  })
  let result = res.result
  expiresTime = new Date(result.expires_at)
  console.log('到期时间=====>', expiresTime)
  obsClient = new ObsClient({
    access_key_id: result.access, // 你的ak
    secret_access_key: result.secret, // 你的sk
    security_token: result.securitytoken,
    server: result.server // 你的endPoint
  })
}
onMounted(async () => {
  await getObsClient()
})
const [channelRegister, { closeDrawer, changeOkLoading, changeLoading }] = useDrawerInner(async (data) => {
  drawerInfo.type = data.type
  drawerInfo.record = cloneDeep(data.record) || {}
  try {
    drawerInfo.serviceLink = data.record.customerServiceUrl
    drawerInfo.servicePhone = data.record.customerServiceMobile
    drawerInfo.sellerSlogan = data.record.merchantSlogans
    drawerInfo.sellerInfo = data.record.merchantContactInfo
    drawerInfo.channelSlogans = data.record.channelSlogans
    drawerInfo.channelContactInfo = data.record.channelContactInfo
    drawerInfo.switchFlag = data.record.switchFlag || 1
    drawerInfo.sendMsgFlag = data.record.sendMsgFlag
    drawerInfo.oneClickInvoiceSoftwareFlag = data.record.oneClickInvoiceSoftwareFlag
    drawerInfo.sptlogo = data.record.sptLogo
    drawerInfo.loginRegisterLogo = data.record.loginRegisterLogo
    drawerInfo.channelDownloadUrl = data.record.channelDownloadUrl
    drawerInfo.channelLoginUrl = data.record.channelLoginUrl
    drawerInfo.mobileChannelLoginUrl = data.record.mobileChannelLoginUrl
    drawerInfo.mobileLoginRegisterLogo = data.record.mobileLoginRegisterLogo
    drawerInfo.yclogo = data.record.ycLogo

    drawerInfo.h5ContactInfo = data.record.h5ContactInfo
    drawerInfo.h5CustomerServiceUrl = data.record.h5CustomerServiceUrl
    drawerInfo.customerServiceQrCode = data.record.customerServiceQrCode
    drawerInfo.h5Slogans = data.record.h5Slogans

    let tabList = cloneDeep(tabObj.tabList)
    let channelBrandConfigurationValue = userModule.permissionActionList.includes(
      permissionCodeMap.channelBrandConfiguration
    )
    let channelPackageConfigurationValue = userModule.permissionActionList.includes(
      permissionCodeMap.channelPackageConfiguration
    )

    tabList[0].isShow = channelBrandConfigurationValue
    tabList[1].isShow = channelPackageConfigurationValue
    tabObj.activeKey = channelBrandConfigurationValue ? '1' : '2'
    tabObj.tabList = tabList
    if (channelPackageConfigurationValue) {
      changeLoading(true)
      let res = await getPackageConfig({
        channelCode: data.record.channelCode
      })
      changeLoading(false)
      drawerInfo.packageSetData = res.result || {}
    }
  } catch (error) {
    changeLoading(false)
  }
})

// 链接处理
const linkHandle = async (type: string) => {
  if (type === 'loginUrl') {
    if (drawerInfo.channelLoginUrl) {
      await toClipboard(drawerInfo.channelLoginUrl)
      message.success('复制链接成功')
    } else {
      try {
        loadingObj.logoLoading = true
        let res = await generateChannelLoginUrlOrDownloadUrl({
          channelCode: drawerInfo.record.channelCode,
          loginOrDownloadUrlFlag: '1'
        })
        loadingObj.logoLoading = false
        if (res.result) {
          drawerInfo.channelLoginUrl = res.result.channelLoginUrl
        }
      } catch (error) {
        loadingObj.logoLoading = false
      }
    }
  } else if (type === 'downloadUrl') {
    if (drawerInfo.channelDownloadUrl) {
      await toClipboard(drawerInfo.channelDownloadUrl)
      message.success('复制链接成功')
    } else {
      try {
        loadingObj.downLoading = true
        let res = await generateChannelLoginUrlOrDownloadUrl({
          channelCode: drawerInfo.record.channelCode,
          loginOrDownloadUrlFlag: '2'
        })
        loadingObj.downLoading = false
        if (res.result) {
          drawerInfo.channelDownloadUrl = res.result.channelDownloadUrl
        }
      } catch (error) {
        loadingObj.downLoading = false
      }
    }
  } else if (type === 'mobileChannelLoginUrl') {
    if (drawerInfo.mobileChannelLoginUrl) {
      await toClipboard(drawerInfo.mobileChannelLoginUrl)
      message.success('复制链接成功')
    } else {
      try {
        loadingObj.mobileChannelLoginUrlLoading = true
        let res = await generateChannelLoginUrlOrDownloadUrl({
          channelCode: drawerInfo.record.channelCode,
          loginOrDownloadUrlFlag: '3'
        })
        loadingObj.mobileChannelLoginUrlLoading = false
        if (res.result) {
          drawerInfo.mobileChannelLoginUrl = res.result.mobileChannelLoginUrl
        }
      } catch (error) {
        loadingObj.mobileChannelLoginUrlLoading = false
      }
    }
  }
}
// tab切换
const tabHandle = (key: string) => {
  tabObj.activeKey = key
}
// 重置信息
const drawerReset = () => {
  changeOkLoading(false)
  changeLoading(false)
  drawerInfo.serviceLink = ''
  drawerInfo.servicePhone = ''
  drawerInfo.sellerSlogan = ''
  drawerInfo.channelSlogans = ''
  drawerInfo.channelContactInfo = ''
  drawerInfo.sellerInfo = ''
  drawerInfo.yclogo = ''
  drawerInfo.mobileLoginRegisterLogo = ''
  drawerInfo.sptlogo = ''
  drawerInfo.packageSetData = {}
  tabObj.activeKey = '1'
  unref(formRef) && unref(formRef).resetFields()
  if (drawerInfo.type !== operateActionType.VIEW) {
    emit('operateSuccess')
  }
}
// 表单校验规则
const getFormRules = {
  serviceLink: [{ required: false, message: '请输入联系客服链接', trigger: 'blur' }],
  servicePhone: [{ required: false, message: '请输入联系客服电话', trigger: 'blur' }],
  sellerSlogan: [{ required: false, message: '请输入商家宣传语', trigger: 'blur' }],
  sellerInfo: [{ required: false, message: '请输入商家联系信息', trigger: 'blur' }],
  switchFlag: [{ required: true, trigger: 'blur' }],
  sendMsgFlag: [{ required: true, trigger: 'blur' }]
}
// 提交数据
const confirmSubmit = async () => {
  try {
    if (tabObj.activeKey === '1') {
      await unref(formRef).validate()
      changeOkLoading(true)
      let reqParam = {
        channelCode: drawerInfo.record?.channelCode || '0',
        customerServiceMobile: drawerInfo.servicePhone || '',
        customerServiceUrl: drawerInfo.serviceLink || '',
        merchantContactInfo: drawerInfo.sellerInfo || '',
        merchantSlogans: drawerInfo.sellerSlogan || '',
        h5ContactInfo: drawerInfo.h5ContactInfo || '',
        h5CustomerServiceUrl: drawerInfo.h5CustomerServiceUrl || '',
        customerServiceQrCode: drawerInfo.customerServiceQrCode || '',
        h5Slogans: drawerInfo.h5Slogans || '',
        channelSlogans: drawerInfo.channelSlogans || '',
        channelContactInfo: drawerInfo.channelContactInfo || '',
        sptLogo: drawerInfo.sptlogo || '',
        loginRegisterLogo: drawerInfo.loginRegisterLogo || '',
        ycLogo: drawerInfo.yclogo || '',
        mobileLoginRegisterLogo: drawerInfo.mobileLoginRegisterLogo || '',
        oneClickInvoiceSoftwareFlag: drawerInfo.oneClickInvoiceSoftwareFlag || 1,
        switchFlag: drawerInfo.switchFlag || 2,
        sendMsgFlag: drawerInfo.sendMsgFlag || 1
      }
      await updateChannelConfig(reqParam)
      message.success('当前品牌配置成功')
      changeOkLoading(false)
      // drawerReset()
    } else if (tabObj.activeKey === '2') {
      let data = packageSetRef.value.submitData()
      if (data) {
        changeOkLoading(true)
        await saveOrUpdate(data)
        message.success('当前套餐配置成功')
        changeOkLoading(false)
      }
    }
  } catch (error) {
    changeOkLoading(false)
  }
}
// 校验文件格式
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('请上传图片文件')
    return false
  }
  return true
}
// 登录logo上传obs和下载展示
const handleDlRequest = async (options: any) => {
  try {
    dlloading.value = true
    await getObsClient()
    drawerInfo.loginRegisterLogo = await obsUpAndDownload(obsClient, options)
    dlloading.value = false
  } catch (error) {
    dlloading.value = false
  }
}
// 数票通logo上传obs和下载展示
const handleSptRequest = async (options: any) => {
  try {
    sptloading.value = true
    await getObsClient()
    console.log('sptoptions===>', options)
    drawerInfo.sptlogo = await obsUpAndDownload(obsClient, options)
    sptloading.value = false
  } catch (error) {
    sptloading.value = false
  }
}
const navScroll = (index: number) => {
  navActive.value = index
  let el = document.getElementsByClassName('scroll-item')[index]
  el.scrollIntoView({ behavior: 'smooth', block: 'start' })
}
const scrollHandleDebounce = (event: Event) => {
  let el = event.target as HTMLElement
  let scrollTop = el.scrollTop
  let clientHeight = el.clientHeight
  let scrollHeight = el.scrollHeight
  let height = scrollTop + clientHeight
  const elements = document.querySelectorAll('.scroll-item')
  elements.forEach((element: any, index: number) => {
    const offsetTop = element.offsetTop
    if (scrollTop >= offsetTop - 48 || height === scrollHeight) {
      navActive.value = index
    }
  })
}
const scrollHandle = (event: Event) => {
  debounce(scrollHandleDebounce, 300)(event)
}
// 业财360logo上传obs和下载展示
const handleYcRequest = async (options: any) => {
  try {
    ycloading.value = true
    await getObsClient()
    console.log('ycoptions===>', options)
    drawerInfo.yclogo = await obsUpAndDownload(obsClient, options)
    ycloading.value = false
  } catch (error) {
    ycloading.value = false
  }
}
// 移动端登录页logo上传obs和下载展示
const handleMobileRequest = async (options: any) => {
  try {
    mobileloading.value = true
    await getObsClient()
    drawerInfo.mobileLoginRegisterLogo = await obsUpAndDownload(obsClient, options)
    mobileloading.value = false
  } catch (error) {
    mobileloading.value = false
  }
}
// H5-联系客服二维码上传obs和下载展示
const handleCustomerRequest = async (options: any) => {
  try {
    customerloading.value = true
    await getObsClient()
    drawerInfo.h5CustomerServiceUrl = await obsUpAndDownload(obsClient, options)
    customerloading.value = false
  } catch (error) {
    customerloading.value = false
  }
}
// pc-联系客服二维码上传obs和下载展示
const handleCustomerQrRequest = async (options: any) => {
  try {
    customerQrloading.value = true
    await getObsClient()
    drawerInfo.customerServiceQrCode = await obsUpAndDownload(obsClient, options)
    customerQrloading.value = false
  } catch (error) {
    customerQrloading.value = false
  }
}
</script>

<style scoped lang="less">
.box-drawer {
  padding: 8px 8px 0;
  .box-product {
    display: flex;
    align-items: flex-start;

    .product-nav {
      width: 176px;
      margin-left: 24px;
      flex-shrink: 0;
      position: relative;
      border-left: 1px solid rgba(0, 0, 0, 0.06);
      .nav-item {
        font-size: 12px;
        margin-bottom: 12px;
        color: #555d6f;
        line-height: 22px;
        padding-left: 16px;
        cursor: pointer;
        &:last-child {
          margin-bottom: 0;
        }
        &.nav-active {
          font-weight: 600;
          color: #4aa353;
          position: relative;
          &::before {
            content: '';
            width: 2px;
            height: 22px;
            background: #4aa353;
            position: absolute;
            left: -1px;
            top: 0;
          }
        }
      }
    }
  }
  .channel-form,
  .channel-view {
    height: calc(100vh - 320px);
    overflow-y: auto;
    border-left: 1px solid #e0e1e6;
    padding-left: 24px;
    .channel-tip {
      height: 51px;
      padding: 14px 16px;
      background: #e9f4fe;
      border-radius: 2px;
      margin-bottom: 16px;
      display: flex;
      align-items: center;
      .tip-txt {
        font-size: 14px;
        color: #192236;
        font-weight: 600;
        line-height: 17px;
      }
    }
  }
}
.drawer-tab {
  border-bottom: 1px solid #e0e1e6;
  margin: 20px 24px 0;
  display: flex;
  align-items: center;
  .tab-item {
    color: #555d6f;
    line-height: 20px;
    margin-left: 40px;
    padding-bottom: 16px;
    position: relative;
    cursor: pointer;
    &.tab-active {
      font-weight: 600;
      color: #4aa353;
      &::after {
        content: '';
        position: absolute;
        bottom: -1px;
        left: 50%;
        width: 40px;
        height: 4px;
        background: #4aa353;
        border-radius: 100px 100px 0 0;
        transform: translateX(-50%);
        z-index: 5;
      }
    }
  }
}
:deep(.scrollbar__wrap) {
  padding: 24px;
}
:deep(.ant-form-item-label) {
  font-weight: 600;
  & > label {
    font-size: 12px;
    color: #192236;
    align-items: center;
  }
}
:deep(.box-desc) {
  margin-top: -16px;
  padding: 0 60px;

  .ant-descriptions-item-label {
    justify-content: end;
    // align-items: center;
    width: 120px;
    font-size: 12px;
    color: #192236;
    font-weight: 600;
  }
  .ant-descriptions-row > th {
    padding-bottom: 6px;
  }
  .ant-descriptions-row > td {
    padding-bottom: 30px;
  }
  .ant-descriptions-row:last-child > td {
    padding-bottom: 0;
  }
  .ant-descriptions-item-content {
    font-size: 14px;
    color: #192236;
    font-weight: 500;
    // height: 20px;
    line-height: 20px;
    position: relative;
    bottom: 1px;
  }
}
:deep(.edit) {
  margin-top: -16px;
  padding: 0 60px;

  .ant-descriptions-item-label {
    justify-content: end;
    align-items: start;
    width: 114px;
    font-size: 12px;
    color: #192236;
    font-weight: 600;
  }
  .ant-descriptions-row > th {
    padding-bottom: 6px;
  }
  .ant-descriptions-row > td {
  }
  .ant-descriptions-item-content {
    font-size: 14px;
    color: #192236;
    font-weight: 500;
    height: 498px;
    line-height: 20px;
    position: relative;
    bottom: -4px;
  }
}
:deep(.preview) {
  .ant-descriptions-item-label {
    position: relative;
    top: 12px;
  }
}

.title {
  padding-left: 12px;
  padding-bottom: 8px;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: @text-color;
  line-height: 22px;
  position: relative;
  border-bottom: 1px solid #e8e8e8;
  &::before {
    content: '';
    width: 4px;
    height: 16px;
    background: @primary-color;
    border-radius: 2px;
    position: absolute;
    left: 0;
    top: 2px;
  }
}

.uploadLogo {
  margin: 40px 0;
  padding: 0 60px;
  &.uploadCustomer {
    padding: 0;
    margin: 0;
  }
  :deep(.ant-image-img) {
    background-color: #f3f4f8;
    width: 100%;
    height: 100%;
  }
  .avatar-uploader {
    position: relative;
    .file-close {
      font-size: 12px;
      color: #c0c0c0;
      position: absolute;
      right: 2px;
      top: 0;
      cursor: pointer;
      z-index: 999;
    }
  }

  :deep(.ant-form-item-no-colon) {
    height: 38px;
    align-items: center;
  }
  // .avatar-uploader > .ant-upload {
  //   width: 240px;
  //   height: 38px;
  // }
  :deep(.ant-upload) {
    position: relative;
    width: auto;
    height: auto;
    .inner-info {
      width: 240px;
      height: 38px;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    img {
      background-color: #f3f4f8;
    }
  }
  .ant-upload-select-picture-card i {
    font-size: 12px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-left: 5px;
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #535d71;
  }
  :deep(.ant-form-itm-no-colon) {
    width: 61px;
    height: 22px;
    font-size: 12px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #192236;
    line-height: 22px;
  }
  :deep(.file-upload) {
    width: 242px;
    height: 40px;
    background: #ffffff;
    border-radius: 2px;
    border: 1px solid #cdcdcd;
  }
  .upload-info {
    color: #c0c0c0;
    font-size: 12px;
    .info-icon {
      font-size: 14px;
      margin-right: 4px;
    }
  }
}
.service {
  margin-top: 40px;
  padding: 0 60px;
  margin-bottom: 40px;
  .service-btn {
    display: flex;
    .btn-link {
      margin-left: 8px;
      &:focus {
        border-color: @primary-color;
        background: @primary-color;
      }
    }
  }
  :deep(.ant-input-affix-wrapper) {
    width: 408px;
  }
  :deep(.ant-form-item-control-input-content) {
    width: 408px;
  }
}
:deep(.ant-switch) {
  background-color: #c0c0c0;
}
.channel-custom {
  display: flex;
  align-items: center;
  // margin-top: 10px;
  padding: 0 60px;
  margin-bottom: 20px;
  color: #c0c0c0;
  font-size: 12px;
  &.channel-custom-invoice {
    padding: 0;
    margin-top: 0;
    margin-bottom: 24px;
  }
  .ant-switch-checked {
    background-color: #4aa353;
  }
  :deep(.ant-form-item) {
    margin-bottom: 0 !important;
  }
  .icon {
    position: relative;
    bottom: -1px;
    font-size: 12px;
    margin-right: 4px;
    margin-left: 10px;
  }
  .describe {
    width: 300px;
    height: 14px;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #c0c0c0;
    line-height: 14px;
  }
}
.staticCode {
  position: relative;
  width: 436px;
  height: 498px;
  background-image: url('../../../../assets/images/staticCode.png');
  &.staticCodeView {
    margin-left: -8px;
  }
  .QRcode {
    width: 128px;
    height: 128px;
    left: 156px;
    top: 175px;
    position: absolute;
    background-image: url('../../../../assets/images/qrCode.png');
  }
  .slogan {
    position: absolute;
    text-align: center;
    left: 31px;
    bottom: 35px;
    width: 376px;
    height: 18px;
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #2a64f6;
    line-height: 18px;
  }
  .contactInfo {
    position: absolute;
    left: 31px;
    bottom: 15px;
    width: 376px;
    text-align: center;
    height: 18px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #192236;
    line-height: 18px;
  }
}
</style>
